import { View } from "@tarojs/components";
import { Component } from "react";
import { createClassFun, parseUrl } from "./utils";
import { LoginComponent } from "./loginComponent";
import "./index.scss"
import loginIcon from "./images/login-logo.png"
import Taro from "@tarojs/taro";
import { getSubsystemBySystemId, loginByWXInfo } from "./api";
import { Toast } from "./toast";
import { LoginResult, LoginResultState, OnShowAppParams, SchoolSimpleInfo } from "./types";
import { getStorage } from "../components/utils";
import { enableTokenCheck } from "./tokenCheck";
import { setBaseSocketUrl, setBaseUrl } from "../../network/baseUrl";
import LgCell from "../components/cell";

const storage = getStorage();

const { rootClass } = createClassFun("weapp-login-page")

/**
 * 进入校园通步骤
 * ①autoNavigate判断query
 *   ①a：带skip
 *      ①aa：带systemID，获取子系统地址==>注入内存==>跳转内部系统
 *      ①ab: 不带systemID，直接跳转options.path
 *   ①b：不带skip：自动/手动登陆，登陆成功后==>把用户/学校数据注入store缓存/app.globalData兼容旧版
 *    ①ba: 带systemID：获取子系统地址==>注入内存==>跳转内部系统
 *    ①bb: 不带systemID：直接跳转options.path
 */


interface WeappLoginPageState {
  systemId: string
  systemName: string
  appId: string
  systemIconUrl: string
  // isAfterUserLogout: boolean
  loginSucUrl: string
  registerPath: string
  showRegisterBtn: boolean
  showLoginComponent: boolean
  showForgetPassword?: boolean
  showVisitorBtn?: boolean
}

export default class WeappLoginPage extends Component<{}, WeappLoginPageState> {

  private app: any

  constructor(props) {
    super(props);
    this.app = Taro.getApp().$app
    this.state = {
      systemId: this.app.loginParams.systemID,
      systemName: this.app.loginParams.systemName,
      appId: this.app.loginParams.appID,
      systemIconUrl: this.app.loginParams.systemIconUrl,
      loginSucUrl: this.app.loginParams.loginSucUrl,
      registerPath: this.app.loginParams.registerPath,
      showRegisterBtn: this.app.loginParams.showRegisterBtn,
      showLoginComponent: false,
      showForgetPassword: false,
      showVisitorBtn: false,
    }
  }

  render() {
    return (
      <View className={rootClass("")}>
        {
          !this.state.showLoginComponent ? "" :
            <LoginComponent
              onLoginSuccess={loginResult => this.handlerLoginSuccess(loginResult)}
              registerPath={this.state.registerPath}
              appId={this.state.appId}
              systemId={this.state.systemId}
              showRegisterBtn={this.state.showRegisterBtn}
              showForgetPassword={this.state.showForgetPassword}
              showVisitorBtn={this.state.showVisitorBtn}
              systemName={this.state.systemName}
              loginIcon={this.state.systemIconUrl || loginIcon} />
        }
      </View>
    )
  }


  async componentDidMount() {
    const isRunLogin = await this.autoNavigate()
    if (isRunLogin) this.autoLogin().then()
  }

  async autoLogin() {
    try {
      await Toast.showLoading()
      const loginResult = await this.wxlogin();
      // console.log('去往登录成功界面', loginResult);
      Toast.hideLoading()
      if (loginResult.state !== LoginResultState.SUCCESS) {
        throw new Error("自动登录失败")
      }
      // console.log('登录状态', loginResult.state);
      this.handlerLoginSuccess(loginResult).then()
    } catch (e) {
      console.error(e)
    }
    this.setState({
      showLoginComponent: true
    })
  }

  async autoNavigate() {
    const onShowOptionsSync = await Taro.getEnterOptionsSync()//报错但能正常使用
    console.log('系统启动参数onShowOptionsSync:', onShowOptionsSync)
    const { skip, systemID } = onShowOptionsSync.query as OnShowAppParams
    const appDefaultUrl = onShowOptionsSync.path

    //存入缓存，不管是否需要登陆，都可能用到
    const app = Taro.getApp().$app
    if (!app.isUserLogout) {
      storage.set('onShowOptionsSyncInfo', JSON.stringify(onShowOptionsSync.query))
    }
    // if (systemID) {
    //    // storage.set('onAppShow_systemID', systemID)
    //    storage.set('onShowOptionsSyncInfo', JSON.stringify(onShowOptionsSync.query))
    // }

    //需要登陆，走登陆再跳转
    if (skip !== "1") return true//走登陆

    //无需登陆，直接跳转
    if (systemID) {
      try {
        await this.navigateBySytemIDWithoutLogin(systemID)
      } catch (e) {
        console.error(e)
        await Taro.redirectTo({
          // url: `${this.state.loginSucUrl}`,
          url: `${Taro.getApp().$app.loginParams.loginSucUrl}`
        })
      }
    } else {
      await Taro.redirectTo({
        url: `/${appDefaultUrl}`
      })
    }
  }

  async wxlogin() {
    try {
      const successCallbackResult = await Taro.login();
      const loginResult = await loginByWXInfo({
        AppID: this.state.appId,
        BrowserInfo: "Andriod",
        LoginIP: "192.168.2.90",
        MacAddress: "   ",
        MachineType: 6,
        Secret: "",
        SysTemID: this.state.systemId,
        encryptedData: "  ",
        iv: "  ",
        js_Code: successCallbackResult.code,
      });
      console.log('登录结果', loginResult);
      return loginResult
    } catch (e) {
      throw e
    }
  }

  async navigateBySytemIDWithoutLogin(systemID) {//为什么是systemID而不是路径，因为网页生成动态二维码的路径不能超过限制，所以只能靠systemId去识别系统而不是直接跳路径
    console.log('不需要登录', systemID)
    switch (systemID) {
      case 'E46': {//门户
        const { webUrl } = await this.getSubsystemInfo('E46')
        storage.set('portalUrl', webUrl)
        await Taro.redirectTo({
          url: '/pages/campusPortal/pages/home/index',
          // fail(error){
          //   Toast.error('页面跳转失败')
          //   console.error(error)
          // }
        })
      }
      default: {
        await Taro.redirectTo({
          url: '/pages/campusPortal/pages/home/index'
        })
        return false
      }
    }
  }

  /**
   *
   * @param systemId 如果传了systemId，不做全局赋值处理，返回参数自行处理
   * @private
   */
  private async getSubsystemInfo(systemId?: string): Promise<any> {
    //获取子系统信息--外部系统必须走
    if (this.app.loginParams.systemID !== 'E43') {
      await Toast.showLoading('系统加载中')
      const currentSchoolInfo = JSON.parse(storage.get('currentSchoolInfo') || '{}')
      const schoolId = currentSchoolInfo.SchoolID || currentSchoolInfo.schoolId
      const subsystemInfo = await getSubsystemBySystemId({
        systemId: systemId || this.app.loginParams.systemID,
        schoolId
      })
      Toast.hideLoading()
      if (systemId) {
        return { webUrl: subsystemInfo.url, wsUrl: subsystemInfo.wsUrl }
      } else {
        if (subsystemInfo.url) {
          this.app.globalData.baseUrl = subsystemInfo.url
          setBaseUrl(subsystemInfo.url)
        } else {
          throw new Error('暂无系统地址，请联系管理员')
        }
        setBaseSocketUrl(subsystemInfo.wsUrl || '')
      }
    }
  }

  private async handlerLoginSuccess(loginResult: LoginResult) {
    try {
      await Toast.success("登录成功")
      //获取校园通跳转过来的参数,并存入必要数据
      const onShowOptionsSync = await Taro.getEnterOptionsSync()//报错但不影响使用
      const extraData = onShowOptionsSync.referrerInfo.extraData;
      const query = onShowOptionsSync.query;
      await this.updateStorage(loginResult, query, extraData);

      //onAppShow页面参数：登陆成功后跳转指定①内部页面②外部子系统页面
      // await this.judgeIfJumpAfterLogin()
      var navPath;
      const typeLib = {
        "addressBook": 260,
        "addressBookNew": 260,
        "schedule": 200
      }
      // 根据系统Id进行跳转
      let systemId
      if (query?.type) {
        navPath =
          systemId = typeLib[query.type] || 200
      } else {
        systemId = 210
      }

      let baseUrl = await this.getSubsystemInfo(systemId)
      let avatarAddr = await this.getSubsystemInfo('260')
      let noticeAddr = await this.getSubsystemInfo('220')
      storage.set('wxNoticeAddr', noticeAddr.webUrl)
      storage.set('avatarAddr', avatarAddr?.webUrl?.split('/Web_WorkPlatform/')[0])
      storage.set('MessageBaseUrl', baseUrl.webUrl)

      //更新数据app的globalData
      this.updateAppGlobalData(loginResult, baseUrl)

      if (this.app.loginParams.onLoginSuccess) {//app.ts登陆参数回调
        await this.app.loginParams.onLoginSuccess()
      }

      if (query?.type) {
        switch (query.type) {
          case 'addressBook':
            navPath = '/pages/addressBookApp/index/index'
            break;
          case 'addressBookNew':
            navPath = '/pages/addressBookAppNew/index/index'
            break;
          case 'schedule':
            navPath = '/pages/scheduleApp/index/index'
            break;
          default:
            navPath = '/pages/messageApp/index' + '?noticeId=' + (query.noticeId || '') + '&taskReleaseId=' + (query.taskReleaseId || '')
        }
      } else {
        navPath = '/pages/messageApp/index' + '?noticeId=' + (query.noticeId || '') + '&taskReleaseId=' + (query.taskReleaseId || '')
      }
      console.log("app储存", Taro.getApp().$app.globalData)
      const self = this
      await Taro.redirectTo({
        // url: this.state.loginSucUrl,
        url: navPath,
        success() {
          enableTokenCheck({//token检测
            appId: self.state.appId,
            schoolId: loginResult.schoolInfo.SchoolID,
            schoolUrl: loginResult.schoolInfo.HostServerUrl,
            systemId: self.state.systemId,
            onTokenRefresh: self.app.loginParams.onTokenRefresh
          })
        }
      })
    } catch (e) {
      await Toast.hideLoading()
      console.error(e)
      await Toast.error(e instanceof Error && e.message ? e.message : "登陆失败")
    }
  }

  private async updateStorage(loginResult: LoginResult, query: Taro.General.IAnyObject, extraData: Taro.General.IAnyObject) {
    storage.set("query", JSON.stringify(query))

    storage.set("openId", loginResult.wxsession.openid)
    storage.set("unionId", loginResult.wxsession.unionid)

    //存入必要的数据
    storage.set("account", loginResult.userInfo.UserID)
    storage.set("token", loginResult.userInfo.Token)
    if (extraData && extraData.lg_ic) {//小程序跳转带参
      storage.set("lg_ic", extraData.lg_ic)
    } else if (loginResult.identityInfos?.length) {//非跳转带参，默认取登陆参数返回第一个身份
      storage.set("lg_ic", loginResult.identityInfos[0]?.IdentityCode || '')
    }
    storage.set("userInfo", JSON.stringify(loginResult.userInfo))

    if (extraData && extraData.moduleInfo) {
      storage.set("moduleInfo", extraData.moduleInfo)
    }

    storage.set("md5Pwd", loginResult.userInfo.Psw)

    //学校缓存信息在自动登陆成功时候也要做一次更新
    const loginSchoolInfo = loginResult.schoolInfo
    const currentSchoolInfo: SchoolSimpleInfo = {
      hostServerUrl: loginSchoolInfo.HostServerUrl,
      id: 0,
      schoolLogoUrl: loginSchoolInfo.SchoolLogoUrl,
      schoolId: loginSchoolInfo.SchoolID,
      schoolName: loginSchoolInfo.SchoolName,
      schoolType: loginSchoolInfo.SchoolType,
      version: loginSchoolInfo.Version
    }
    storage.set('currentSchoolInfo', JSON.stringify(currentSchoolInfo))

    //更新initMiddlePage页面判断依据缓存
    storage.set('firstChoseType', 'user')//user visitor
  }

  private updateAppGlobalData(loginResult: LoginResult, baseUrl) {
    this.app.globalData.loginInfo = loginResult
    this.app.globalData.userInfo = loginResult.userInfo
    this.app.globalData.identityInfos = loginResult.identityInfos
    this.app.globalData.userName = loginResult.userInfo.UserName
    this.app.globalData.Token = loginResult.userInfo.Token
    this.app.globalData.schoolID = loginResult.schoolInfo.SchoolID
    this.app.globalData.groupID = loginResult.userInfo.GroupID
    this.app.globalData.gender = loginResult.userInfo.Gender
    this.app.globalData.userID = loginResult.userInfo.UserID
    this.app.globalData.userType = loginResult.userInfo.UserType
    this.app.globalData.schoolUrl = loginResult.schoolInfo.HostServerUrl
    this.app.globalData.schoolLevel = loginResult.schoolInfo.SchoolLevel
    this.app.globalData.Psw = loginResult.userInfo.Psw
    this.app.globalData.localuserInfo = loginResult.userInfo
    this.app.globalData.isLogin = true
    this.app.globalData.unionID = loginResult.wxsession.unionid
    this.app.globalData.openID = loginResult.wxsession.openid
    this.app.globalData.baseUrl = baseUrl.webUrl
    let insidePhothoUrl = loginResult.userInfo.PhotoPath;
    const { host: mapAddrResult } = parseUrl(loginResult.schoolInfo.HostServerUrl)//iscb.lancooedu.com 120.196.79.139
    const { host: userPhotoUrlIp } = parseUrl(insidePhothoUrl)//192.168.122.124 from http://192.168.122.124:22101/http_basic/UserInfo/Avatar/Default/Nopic001.jpg
    if (mapAddrResult) {
      this.app.globalData.schoolIP = mapAddrResult
      this.app.globalData.userPhotoUrl = insidePhothoUrl.replace(userPhotoUrlIp, mapAddrResult);//http://120.196.79.139:22101/http_basic/UserInfo/Avatar/Default/Nopic001.jpg
    }
    //家长身份进入realUserID采用学生账号调用接口
    if (this.app.globalData.userType == "3") {
      this.app.globalData.realUserID = this.app.globalData.userID.substr(3);
    } else {
      this.app.globalData.realUserID = this.app.globalData.userID;
    }
  }
}
